import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import routes from './asyncRoutesMap.ts'
import { useRouteStore } from '@/store/modules/route.ts'
const { setIndexPath, setVerticalRoutes } = useRouteStore()
const router = createRouter({
  history: createWebHashHistory(),
  // 真正的路由表是要拍平的，这里暂时没拍平，这个routes的作用是为了渲染菜单栏
  routes: routes,
})
export default router

router.beforeEach((to, from, next) => {
  // 当前的路由中的meta中的subMenu为true时，跳转到其第一个子路由
  if (to.meta.subMenu) {
    const path = to.matched.slice(-1)[0].children[0].path
    return next(path)
  }
  // mixin布局下顶部菜单栏的选中项路径,用于顶部菜单高亮
  setIndexPath(to.matched[1]?.path)
  // mixin布局左侧菜单设置
  const routeItem = to.matched[1]
  if (routeItem?.children.length) {
    setVerticalRoutes(routeItem?.children)
  } else {
    setVerticalRoutes([routeItem] as RouteRecordRaw[])
  }
  next()
})
